package com.shujia.flink.kafka;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo1KakaSource {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")//kafka集群列表
                .setTopics("students")//指定消费的topic
                .setGroupId("my-group")//指定消费者组

                // 从消费组提交的位点开始消费，如果提交位点不存在，使用最早位点
                //.setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
                // 从最早位点开始消费
                //.setStartingOffsets(OffsetsInitializer.earliest())
                // 从最末尾位点开始消费
                .setStartingOffsets(OffsetsInitializer.latest())

                .setValueOnlyDeserializer(new SimpleStringSchema())//指定读取数据的格式
                .build();

        //使用kafka source
        DataStreamSource<String> studentDS = env
                .fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");

        studentDS.print();

        env.execute();
    }
}
